<template>
  <div id="viewDiv">
    <legendLayer />
    <div class="computeArea" @click="area">计算</div>
  </div>
</template>

<script>
import { EsriNameSpace } from '../api/arcgis/esri-namespace'
import {
  mapCenter,
  mapZoom,
  NjSpatialReference,
} from '../../public/arcgisParam/arcgisParam'
import { AddGraphics } from '../lib/addGraphic'
import { CreateSymbol } from '../lib/createSymbol'
import ArcgisUtils from '../lib/arcgisUtils'
import legendLayer from '../views/Legend-layer'

export default {
  name: 'NJScenic',
  components: {
    legendLayer,
  },
  data() {
    return {
      EsriNameSpace: new EsriNameSpace(),
      CreateSymbol: new CreateSymbol(),
      ArcgisUtils: new ArcgisUtils(),
      spatialReference: '',
    }
  },
  mounted() {
    //接收数据
    this.$bus.$on('gggg-click', (layerId) => {
      this.ArcgisUtils.setLayerVisible(this.ZGMap, layerId)
    })

    this.EsriNameSpace.initNameSpace().then(() => {
      this.spatialReference = this.EsriNameSpace.SpatialReference({
        wkt: NjSpatialReference,
      })
      // 初始化地图
      this.initMap(mapCenter, mapZoom).then((initMapData) => {
        this.clickEventLayer(initMapData.view)
        this.moveEventLayer(initMapData.view)
        this.addGraphic = new AddGraphics(initMapData.map, this.EsriNameSpace)
        console.log('加addGraphic类')
        // 加面
        const line10Layer = this.addGraphic.createGraphicsLayer('line10')
        this.ZGMap.add(line10Layer)

        // 编辑图层
        const hh = this.addGraphic.createGraphicsLayer('sketch')
        this.addGraphic.mapAddLayer(initMapData.map, hh)
        const sketch = this.EsriNameSpace.Sketch({
          layer: hh,
          view: initMapData.view,
          creationMode: 'single',
          layout: 'vertical',
        })
        initMapData.view.ui.add(sketch, 'top-right')
      })
    })
  },
  methods: {
    initMap(center, zoom) {
      return new Promise(async (resolve, reject) => {
        console.log('初始化地图--ING')
        const NJRSLayers = this.EsriNameSpace.WebTileLayer({
          urlTemplate: 'http://localhost:8089/njMap/{level}/{col}/{row}.jpg',
        })

        const elevLyr = this.EsriNameSpace.ElevationLayer({
          // Custom elevation service
          url:
            'http://localhost:6080/arcgis/rest/services/02NJPeopleSafe/elevationNj/ImageServer',
          // 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer',
        })

        this.ZGMap = this.EsriNameSpace.Map({
          basemap: {
            // baseLayers: [NJRSLayers],
          },
          // ground: 'world-elevation',
          // spatialReference: this.spatialReference,
        })
        this.ZGMap.ground.layers.add(elevLyr)
        this.ZGMapView = this.EsriNameSpace.SceneView({
          container: 'viewDiv',
          map: this.ZGMap,
          camera: {
            position: center,
            heading: 0,
            tilt: 60,
          },
        })
        resolve({ map: this.ZGMap, view: this.ZGMapView })
      })
    }, // end

    // 鼠标的点击事件
    clickEventLayer(mapView) {
      mapView.on('click', (event) => {
        mapView.hitTest(event).then((response) => {
          console.log(response)
          if (response.results.length > 0) {
            const currentGraphic = response.results.filter((result) => {
              return result.graphic.layer
            })[0].graphic
            // console.log(currentGraphic)

            var lat = Math.round(event.mapPoint.latitude * 1000000) / 1000000
            var lon = Math.round(event.mapPoint.longitude * 1000000) / 1000000
            var measureThisAction = {
              title: 'Measure Length',
              id: 'measure-this',
              image:
                'https://developers.arcgis.com/javascript/latest/sample-code/popup-actions/live/Measure_Distance16.png',
            }
            mapView.popup.open({
              // Set the popup's title to the coordinates of the location
              // title: 'Reverse geocode: [' + lon + ', ' + lat + ']',
              location: event.mapPoint, // Set the location of the popup to the clicked location
              actions: [measureThisAction],
              container:
                "<div style='max-width: 156px;overflow: hidden;height: 100%;margin-top: 13px;word-wrap:break-word'>" +
                "<p style='font-size: 14px;color: #333333; margin: 0;'>" +
                '分所给他被告人发我' +
                '</p>' +
                '</div>',
            })

            /**
             * 点击有Graphic数据的时候，如果是相应的面数据，改变相应的样式
             */
            if (currentGraphic.layer.title == 'polygon2020') {
              for (const graphic of currentGraphic.layer.graphics.items) {
                // 面的初始样式
                graphic.symbol = this.CreateSymbol.createSimpleFillSymbol(
                  [0, 200, 179],
                  'solid',
                  '#33333',
                  5
                )
              }
              // 面的选择样式
              currentGraphic.symbol = this.CreateSymbol.createSimpleFillSymbol(
                'blue',
                'solid',
                'darkblue',
                1
              )
            }
          }
        })
      })
    }, // end click

    // 鼠标移动事件
    moveEventLayer(mapView) {
      mapView.on('pointer-move', (event) => {
        mapView.hitTest(event).then((response) => {
          if (response.results.length > 0) {
            document.body.style.cursor = 'pointer'
          } else {
            document.body.style.cursor = 'default'
          }
        })
      })
    }, // end moveEvent
    area() {
      const sketchLayer = this.ZGMap.findLayerById('sketch')
      const polygon2020 = this.ZGMap.findLayerById('polygon2020')

      // console.log(sketchLayer)
      this.computeArea(polygon2020, sketchLayer)
    }, // area
    computeArea(polygonLayer, drawLayer) {
      // 遍历已知的面 和 画的面进行拓扑关系检查
      /**
       * 1、已知的面包含画的面，计算画的面的面积
       * 2、已知的面与画的面相交，计算相交的面的面积
       * 3、画的面与多个已知的相交，计算相交的面的面积
       */
      const geoEngine = this.EsriNameSpace.geometryEngine
      const webMercatorUtils = this.EsriNameSpace.webMercatorUtils
      const polygonItems = polygonLayer.graphics.items
      const drawItems = drawLayer.graphics.items
      console.log(polygonItems)

      for (const polygonItem of polygonItems) {
        for (const drawItem of drawItems) {
          const ll = webMercatorUtils.webMercatorToGeographic(drawItem.geometry)
          if (geoEngine.intersects(ll, polygonItem.geometry)) {
            const kk = geoEngine.intersect(ll, polygonItem.geometry)
            const hhh = geoEngine.geodesicArea(kk, 'square-kilometers')
            console.log(hhh)
          }
        }
      }
    },
  }, //end methods
}
</script>

<style lang="less" scoped>
#viewDiv {
  width: 100vw;
  height: 100vh;
}

#viewDiv
  > div.esri-view-root
  > div.esri-ui
  > div.esri-ui-inner-container.esri-ui-manual-container
  > div.esri-component.esri-popup.esri-popup--aligned-top-center.esri-popup--shadow {
  background-color: rgba(212, 25, 123, 0.7);
}

// .esri-popup__pointer-direction {
//   width: 0;
//   height: 0;
// }
// .esri-popup__main-container {
//   background-color: red;
// }
// .esri-feature {
//   background-color: blue;
// }
// .esri-popup__button:hover {
//   background: #000;
// }
.computeArea {
  position: absolute;
  bottom: 100px;
  left: 100px;
  background-color: blue;
}
</style>
